package cn.fbs.service.core;

import cn.fbs.dao.dm.*;
import cn.fbs.enums.MediaEnum;
import cn.fbs.model.TDataInfo;
import cn.fbs.model.TImageInfo;
import cn.fbs.model.TVideoInfo;
import cn.fbs.model.dm.UserExamine;
import cn.fbs.model.dm.UserGroup;
import cn.fbs.param.DataParam;
import cn.fbs.param.ImageParam;
import cn.fbs.param.UploadParam;
import cn.fbs.param.VideoParam;
import cn.fbs.service.AssignService;
import cn.fbs.service.CategoryService;
import cn.fbs.service.ImageDataService;
import cn.fbs.vo.DataEvaluateVo;
import cn.fbs.vo.ImageEvaluateVo;
import cn.fbs.vo.VideoEvaluateVo;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Log
public class ReviewService {

    @Value(("${maxJoinNum}"))
    private int maxJoinNum;

    @Autowired
    private DMDataInfoMapper dataInfoMapper;
    @Autowired private DMImageInfoMapper imageInfoMapper;
    @Autowired private DMVideoInfoMapper videoInfoMapper;
    @Autowired private DMQbCategoryConnectionMapper connectionMapper;
    @Autowired private DMCodeCategoryTypeMapper categoryTypeMapper;
    @Autowired private UserExamineMapper examineMapper;
    @Autowired private UserGroupMapper userGroupMapper;
    @Autowired private CategoryService categoryService;
    @Autowired private ImageService imageService;
    @Autowired private VideoService videoService;
    @Autowired private ImageDataService imageDataService;
    @Autowired private AssignService assignService;

    @Transactional(rollbackFor = Exception.class)
    public String examineZCImage(ImageParam uploadParam) throws Exception {
        ArrayList<Long> ids = uploadParam.getIds();
        if (ids == null || ids.size() == 0) {
            return "请传入需要进行审核的主键ids";
        }
        Long userId = uploadParam.getUserId();
        if (uploadParam.getId()==null) {
            /**
             * 批量审核通过
             */
            for (Long dataId : ids) {
                /**
                 * 会审表进行记录
                 */
                UserExamine userExamine = new UserExamine();
                userExamine.setUserId(userId);
                userExamine.setMessageId(dataId);
                userExamine.setCreateTime(new Date());
                userExamine.setMediaType(MediaEnum.IMAGE.getIndex());
//                userExamine.setExamineType(ExamineEnum.checked.getIndex());
                userExamine.setExamineType(uploadParam.getExamineType());
                TImageInfo tImageInfo = imageInfoMapper.selectByPrimaryKey(dataId);
                String targetType = tImageInfo.getTargetType();
                userExamine.setTargetId(targetType);
                Long groupID = userGroupMapper.selectGroupIdbyUserId(userId);
                userExamine.setGroupId(groupID);
                /**
                 * 根据图像主键查询图像详情，根据详情中的目标主键查询对应的小组
                 */
                examineMapper.insertSelective(userExamine);
                /**
                 * 数据表进行修改
                 */
//                TImageInfo innerImage = new TImageInfo();
//                innerImage.setId(dataId);
//                if (uploadParam.getExamineType()!=2){
//                    innerImage.setIsExamine(ExamineEnum.checked.getIndex());
//                }
                Integer isExamine = getIsExamine(groupID, userId, uploadParam);
//                if (isExamine.startsWith("500")){
//                    return isExamine;
//                }

                tImageInfo.setIsExamine(isExamine);
                imageInfoMapper.updateByPrimaryKeySelective(tImageInfo);


            }
            return "200,审核完成";
        }
        /**
         * 单条会审修改会审表
         *
         */
        Long dataId = ids.get(0);
        uploadParam.setId(dataId);
        UserExamine userExamine = new UserExamine();
        userExamine.setUserId(userId);
        userExamine.setMessageId(dataId);
        userExamine.setCreateTime(new Date());
        userExamine.setMediaType(MediaEnum.IMAGE.getIndex());
        userExamine.setExamineType(uploadParam.getExamineType());
        userExamine.setMemo(uploadParam.getExpertMemo());
        TImageInfo tImageInfo = imageInfoMapper.selectByPrimaryKey(dataId);
        String targetType = tImageInfo.getTargetType();
        userExamine.setTargetId(targetType);
        Long groupId = userGroupMapper.selectGroupIdbyUserId(userId);
        userExamine.setGroupId(groupId);
        /**
         * 根据图像主键查询图像详情，根据详情中的目标主键查询对应的小组
         */
        /**
         * 若已存在则修改，不存在则新增
         */
        insertUserExamine(userExamine);

        /**
         * 开始编辑逻辑
         */
        String fileName = uploadParam.getFileName();
        if (fileName.endsWith("****")) {
            String bm = String.format("%04d", Integer.parseInt(categoryTypeMapper.getSequence()));
            String replace = fileName.replace("****", bm);
            uploadParam.setFileName(replace);
        }
        TImageInfo imageInfo = new TImageInfo();
        imageInfo.setUpdateDate(new Date());
        BeanUtils.copyProperties(uploadParam, imageInfo);
        File file = null;
        if (StringUtils.isNotBlank(uploadParam.getRealFileUrl())) {
            file = new File(uploadParam.getRealFileUrl());
        }
        if (file != null && file.exists()) {
            assignService.giveImageInfo(uploadParam, imageInfo);
        }
        if (StringUtils.isNotBlank(imageInfo.getTargetType())) {
            if (imageInfoMapper.selectCountBytargetXh(imageInfo.getTargetType(), imageInfo.getId()) >= maxJoinNum) {
                return "400,目标关联数据超过最大限制!";
            }
        }

//        if (imageInfo.getIsExamine()!=1){
//            return "500,";
//        }
        Integer isExamine = getIsExamine(groupId, userId, uploadParam);
        imageInfo.setIsExamine(isExamine);
        imageInfoMapper.updateByPrimaryKeySelective(imageInfo);
        /**
         * 处理标签信息-删除原有标签，添加新标签
         */
        if (uploadParam.getCategoryIds() != null) {
            connectionMapper.deleteByMessageId(uploadParam.getId());
            if (uploadParam.getCategoryIds().size() > 0) {
                categoryService.insertCategory(uploadParam.getCategoryIds(), uploadParam.getOperator(), imageInfo.getId(), 2);
            }
        }
        return "200,操作成功";
    }

    @Transactional(rollbackFor = Exception.class)
    public String examineZCVideo(VideoParam uploadParam) throws Exception {
        ArrayList<Long> ids = uploadParam.getIds();
        if (ids == null || ids.size() == 0) {
            return "请传入需要进行审核的主键ids";
        }
        Long userId = uploadParam.getUserId();
        if (uploadParam.getId()==null) {
            /**
             * 批量审核通过
             */
            for (Long dataId : ids) {
                /**
                 * 会审表进行记录
                 */
                UserExamine userExamine = new UserExamine();
                userExamine.setUserId(userId);
                userExamine.setMessageId(dataId);
                userExamine.setCreateTime(new Date());
                userExamine.setMediaType(MediaEnum.IMAGE.getIndex());
//                userExamine.setExamineType(ExamineEnum.checked.getIndex());
                userExamine.setExamineType(uploadParam.getExamineType());
                TVideoInfo bean = videoInfoMapper.selectByPrimaryKey(dataId);
                String targetType = bean.getTargetType();
                userExamine.setTargetId(targetType);
                Long groupID = userGroupMapper.selectGroupIdbyUserId(userId);
                userExamine.setGroupId(groupID);
                /**
                 * 根据图像主键查询图像详情，根据详情中的目标主键查询对应的小组
                 */
                examineMapper.insertSelective(userExamine);
                /**
                 * 数据表进行修改
                 */
                Integer isExamine = getIsExamine(groupID, userId, uploadParam);
                bean.setIsExamine(isExamine);
                videoInfoMapper.updateByPrimaryKeySelective(bean);
            }
            return "200,审核完成";
        }
        /**
         * 单条会审修改会审表
         *
         */
        Long dataId = ids.get(0);
        uploadParam.setId(dataId);
        UserExamine userExamine = new UserExamine();
        userExamine.setUserId(userId);
        userExamine.setMessageId(dataId);
        userExamine.setCreateTime(new Date());
        userExamine.setMediaType(MediaEnum.IMAGE.getIndex());
        userExamine.setExamineType(uploadParam.getExamineType());
        userExamine.setMemo(uploadParam.getExpertMemo());
        TVideoInfo bean = videoInfoMapper.selectByPrimaryKey(dataId);
        String targetType = bean.getTargetType();
        userExamine.setTargetId(targetType);
        Long groupId = userGroupMapper.selectGroupIdbyUserId(userId);
        userExamine.setGroupId(groupId);
        insertUserExamine(userExamine);


        String fileName = uploadParam.getFileName();
        if (fileName.endsWith("****")) {
            String bm = String.format("%04d", Integer.parseInt(categoryTypeMapper.getSequence()));
            String replace = fileName.replace("****", bm);
            uploadParam.setFileName(replace);
        }
        TVideoInfo videoInfo = new TVideoInfo();
        videoInfo.setUpdateDate(new Date());
        BeanUtils.copyProperties(uploadParam, videoInfo);
//        String fileName = generatorFileName(uploadParam.getCategoryIds(), uploadParam.getZzdx());
//        videoInfo.setFileName(fileName);
//        if (fileName.startsWith("500")) {
//            return fileName;
//        }
        File file = null;
        if (StringUtils.isNotBlank(uploadParam.getRealFileUrl())) {
            file = new File(uploadParam.getRealFileUrl());
        }
        if (file != null && file.exists()) {
            assignService.giveVideoInfo(uploadParam, videoInfo);
        }

        if (StringUtils.isNotBlank(videoInfo.getTargetType())) {
            if (videoInfoMapper.selectCountBytargetXh(videoInfo.getTargetType(), videoInfo.getId()) >= maxJoinNum) {
                return "400,目标关联数据超过最大限制!";
            }
        }


        Integer isExamine = getIsExamine(groupId, userId, uploadParam);
        videoInfo.setIsExamine(isExamine);
        videoInfoMapper.updateByPrimaryKeySelective(videoInfo);
        /**
         * 处理标签信息-删除原有标签，添加新标签
         */
        if (uploadParam.getCategoryIds() != null) {
            connectionMapper.deleteByMessageId(uploadParam.getId());
            if (uploadParam.getCategoryIds().size() > 0) {
                categoryService.insertCategory(uploadParam.getCategoryIds(), uploadParam.getOperator(), videoInfo.getId(), 3);
            }
        }
        return "200,操作成功";
    }

    @Transactional(rollbackFor = Exception.class)
    public String examineDataInfo(DataParam uploadParam) throws Exception {
        ArrayList<Long> ids = uploadParam.getIds();
        if (ids == null || ids.size() == 0) {
            return "请传入需要进行审核的主键ids";
        }
        Long userId = uploadParam.getUserId();
//        if (uploadParam.getId()==null) {
//            /**
//             * 批量审核通过
//             */
//            for (Long dataId : ids) {
//                /**
//                 * 会审表进行记录
//                 */
//                UserExamine userExamine = new UserExamine();
//                userExamine.setUserId(userId);
//                userExamine.setMessageId(dataId);
//                userExamine.setCreateTime(new Date());
//                userExamine.setMediaType(MediaEnum.IMAGE.getIndex());
////                userExamine.setExamineType(ExamineEnum.checked.getIndex());
//                userExamine.setExamineType(uploadParam.getExamineType());
//                TDataInfo bean = dataInfoMapper.selectByPrimaryKey(dataId);
//                String targetType = bean.getTargetType();
//                userExamine.setTargetId(targetType);
//                Long groupID = userGroupMapper.selectGroupIdbyUserId(userId);
//                userExamine.setGroupId(groupID);
//                /**
//                 * 根据图像主键查询图像详情，根据详情中的目标主键查询对应的小组
//                 */
//                examineMapper.insertSelective(userExamine);
//                /**
//                 * 数据表进行修改
//                 */
//                Integer isExamine = getIsExamine(groupID, userId, uploadParam);
//                bean.setIsExamine(isExamine);
//                dataInfoMapper.updateByPrimaryKeySelective(bean);
//
//
//            }
//            return "200,审核完成";
//        }
        /**
         * 单条会审修改会审表
         *
         */
        Long dataId = ids.get(0);
        uploadParam.setId(dataId);
        UserExamine userExamine = new UserExamine();
        userExamine.setUserId(userId);
        userExamine.setMessageId(dataId);
        userExamine.setCreateTime(new Date());
        userExamine.setMediaType(MediaEnum.IMAGE.getIndex());
        userExamine.setExamineType(uploadParam.getExamineType());
        userExamine.setMemo(uploadParam.getExpertMemo());
//        TDataInfo bean = dataInfoMapper.selectByPrimaryKey(dataId);
//        String targetType = bean.getTargetType();
        userExamine.setTargetId("无");
        Long groupId = userGroupMapper.selectGroupIdbyUserId(userId);
        userExamine.setGroupId(groupId);
        insertUserExamine(userExamine);


        String fileName = uploadParam.getFileName();
        if (fileName.endsWith("****")) {
            String bm = String.format("%04d", Integer.parseInt(categoryTypeMapper.getSequence()));
            String replace = fileName.replace("****", bm);
            uploadParam.setFileName(replace);
        }
        TDataInfo dataInfo = new TDataInfo();
        BeanUtils.copyProperties(uploadParam, dataInfo);
        dataInfo.setUpdateDate(new Date());
        File file = null;
        if (StringUtils.isNotBlank(uploadParam.getRealFileUrl())) {
            file = new File(uploadParam.getRealFileUrl());
        }
        if (file != null && file.exists()) {
            assignService.giveDataInfo(uploadParam, dataInfo);
        }



//        Integer isExamine = getIsExamine(groupId, userId, uploadParam);
        dataInfo.setIsExamine(uploadParam.getExamineType());
        dataInfoMapper.updateByPrimaryKeySelective(dataInfo);
        /**
         * 处理标签信息-删除原有标签，添加新标签
         */
        // 2021/3/15 可以优化一下--判断是否有重复的，如果有重复的数据，就将重复数据剔除
        /*
        没有必要，数据插入速度相比查询和删除要快-删除和查询速度区别不大
         */
        if (uploadParam.getCategoryIds() != null) {
            connectionMapper.deleteByMessageId(uploadParam.getId());
            if (uploadParam.getCategoryIds().size() > 0) {
                categoryService.insertCategory(uploadParam.getCategoryIds(), uploadParam.getOperator(), dataInfo.getId(), 1);
            }
        }
        return "操作成功";
    }

    private Integer getIsExamine(Long groupId, Long userId, UploadParam uploadParam) throws Exception {
        /**
         * 判断最终结果是否通过
         * 首先判断是否是终审
         * 如果是终审
         * 直接修改审核状态
         * 如果不是终审
         * 审核意见是废弃，则直接废弃
         * 如果审核意见是存疑，则直接将状态修改为存疑
         * 如果审核意见是通过，则判断是否是全部通过，若是，则修改审核状态为通过，若不是，则状态应为未审核
         */

        Integer finalCheck = uploadParam.getFinalCheck();
        Integer examineType = uploadParam.getExamineType();
//        if (imageInfo.getIsExamine()==null){
//            imageInfo.setIsExamine(1);
//        }
        /**
         * 终审
         */
        if (finalCheck ==null){
            throw new Exception("500,请传是否是终审的标志位--finalCheck") ;
        }
        if (finalCheck == 2) {
            return examineType;
        }
        /**
         * 非终审
         */
        if (finalCheck == 1) {
            if ( examineType== 4||examineType==3) {
                /**
                 * 在修改前确认此数据是未处理的数据，
                 */
                return examineType;
            }else if (examineType ==2){
//                if (imageInfo.getIsExamine()!=1){
//                    return "500,此条数据已审核完成,审核状态为,不可继续进行修改。";
//                }
                /**
                 * 若某一专家认为通过，则去库中查看是否小组内的其他人都认为通过，若都认为则判定为通过，若不通过
                 * 先查出小组下共有几人，再查出有几个专家提交了通过的意见--不需要考虑其他专家提交了其他意见的数据
                 * 上面已经做了处理
                 */
                List<UserGroup> list=userGroupMapper.countMyGroupUser(userId);
                Integer checkedSize=examineMapper.countByGroupId(groupId,uploadParam.getId());
                if (list.size()==checkedSize){
                    return 2;
                }else {
                    return 1;
                }
            }

        }
        return 1;
    }

    private void insertUserExamine(UserExamine userExamine) {
        UserExamine existBean=examineMapper.ifExist(userExamine);
        if (existBean==null){
            examineMapper.insertSelective(userExamine);
        }else {
            userExamine.setId(existBean.getId());
            examineMapper.updateByPrimaryKeySelective(userExamine);

        }
    }



    public DataEvaluateVo getDataEvaluate(Long id) {
        System.out.println("getDataEvaluate_1");
        return dataInfoMapper.getDataEvaluate(id);
    }

    public VideoEvaluateVo getVideoEvaluate(Long id) {
        System.out.println("getDataEvaluate_2");
        return videoInfoMapper.getVideoEvaluate(id);
    }

    public ImageEvaluateVo getImageEvaluate(Long id) {
        ImageEvaluateVo imageEvaluate = imageInfoMapper.getImageEvaluate(id);
        return imageEvaluate;
    }


    public void tempExamine(int fileType, int examineType, long id) {

        if (fileType==(MediaEnum.IMAGE.getIndex())){
            TImageInfo tImageInfo = new TImageInfo();
            tImageInfo.setId(id);
            tImageInfo.setIsExamine(examineType);
            imageInfoMapper.updateByPrimaryKeySelective(tImageInfo);
        }
        if (fileType==(MediaEnum.VIDEO.getIndex())){
            TVideoInfo tVideoInfo = new TVideoInfo();
            tVideoInfo.setId(id);
            tVideoInfo.setIsExamine(examineType);
            videoInfoMapper.updateByPrimaryKeySelective(tVideoInfo);

        }
        if (fileType==(MediaEnum.DATA.getIndex())){
            TDataInfo tDataInfo = new TDataInfo();
            tDataInfo.setId(id);
            tDataInfo.setIsExamine(examineType);
            dataInfoMapper.updateByPrimaryKeySelective(tDataInfo);

        }

    }
}
